﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Hands.UriRewrite
{
    internal class UriRootPath : IRewrite
    {
        private readonly string rootPath = null;

        private Regex branchPathRegex = null;

        private readonly Dictionary<string, UriBranchPath> branchPathSet = new Dictionary<string, UriBranchPath>();

        internal UriRootPath(string rootPath)
        {
            this.rootPath = rootPath;
        }

        internal void addBranchPathRegex(Regex regex)
        {
            branchPathRegex = regex;
        }

        internal void addUriBranch(string branch, UriBranchPath uriBranch)
        {
            if (!this.branchPathSet.ContainsKey(branch))
            {
                this.branchPathSet.Add(branch, uriBranch);
            }
        }

        public string rewrite(string uri)
        {
            string branchUri = uri.Replace(rootPath, string.Empty);
            string branchPath = branchPathRegex.Match(branchUri).Value;
            if (branchPathSet.ContainsKey(branchPath))
            {
                IRewrite rewrite = branchPathSet[branchPath];
                return rewrite.rewrite(branchUri);
            }
            else
            {
                return string.Empty;
            }

        }
    }
}
